/*
    Geocache: some utilities for managing and visualizing geocache information
    Copyright (C) 2008  Gary Jackson

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/*
 * SmartName.java
 */

package com.thegbomb.geocache;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Gary Jackson
 */
public class SmartName {
    static private Logger logger = Logger.getLogger(SmartName.class.getName());
    
    private int length;
    private Map<String,String> forward;
    private Set<String> reverse;
    
    /**
     * Creates a new instance of SmartName
     */
    public SmartName(int length) {
        if (length <= 0) throw new IllegalArgumentException("length must be greater than zero");
        this.length = length;
        this.forward = new HashMap<String,String>();
        this.reverse = new HashSet<String>();
    }
    
    public String convert(String waypoint, String input) {
        String x = this.forward.get(waypoint);
        if (x != null)
            return x;
        
        StringBuffer xbuf;
        String sanitize = sanitize(input);
        if (sanitize.length() != 0)
            xbuf = new StringBuffer(xform(sanitize));
        else {
            xbuf = new StringBuffer(waypoint.substring(0, (this.length<waypoint.length())?this.length:waypoint.length()));
        }
        x = xbuf.toString();
        int i = 2;
        while (reverse.contains(x)) {
            String si = Integer.toString(i++);
            if (si.length() < xbuf.length()) {
                xbuf.replace(xbuf.length() - si.length(), xbuf.length(), si);
            } else {
                throw new RuntimeException("could not generate a name for " + input + " at waypoint " + waypoint);
            }
            x = xbuf.toString();
        }
        
        this.forward.put(waypoint, x);
        this.reverse.add(x);
        
        return x;
    }
    
    private String sanitize(String input) {
        String result = input;
        
        // remove entities
        result = result.replaceAll("&[a-zA-Z0-9-]+?;", "");
        
        // remove other garbage
        result = result.replaceAll("[^a-zA-Z0-9\\s-]+", "");
        
        return result;
    }
    
    private String xform(String input) {
        // Capitalize initials and strip spaces
        String[] split = input.trim().split("\\s+");
        int length = 0;
        for (int i = 0; i < split.length; i++) {
            StringBuffer buf = new StringBuffer(split[i].length());
            buf.append(split[i].substring(0,1).toUpperCase());
            buf.append(split[i].substring(1).toLowerCase());
            split[i] = buf.toString();
            length += buf.length();
        }
        
        // If it doesn't fit, replace You with U
        if (length > this.length) {
            length = 0;
            for (int i = 0; i < split.length; i++) {
                split[i] = split[i].replaceAll("You", "U");
                length += split[i].length();
            }
        }
        
        // If it doesn't fit, remove 'The'
        if (length > this.length) {
            length = 0;
            for (int i = 0; i < split.length; i++) {
                if (split[i].equals("The"))
                    split[i] = "D";
                length += split[i].length();
            }
        }
        
        // If it doesn't fit, remove vowel sequences bounded by consonants
        if (length > this.length) {
            Pattern p = Pattern.compile("([bcdfghjklmnpqrstvwxyz])[aeiou]+([bcdfghjklmnpqrstvwxyz])",
                    Pattern.CASE_INSENSITIVE);
            length = 0;
            for (int i = 0; i < split.length; i++) {
                Matcher m = p.matcher(split[i]);
                StringBuffer sb = new StringBuffer(split[i].length());
                if (m.find()) {
                    m.appendReplacement(sb, m.group(1) + m.group(2));
                    m.usePattern(Pattern.compile("[aeiou]+([bcdfghjklmnpqrstvwxyz])"));
                }
                while (m.find()) {
                    m.appendReplacement(sb, m.group(1));
                }
                m.appendTail(sb);
                split[i] = sb.toString();
                
                length += split[i].length();
            }
        }
        
        StringBuffer buf = new StringBuffer(length);
        for (int i = 0; i < split.length; i++) {
            buf.append(split[i]);
        }
        String result = buf.toString();
        
        // If it doesn't fit, truncate
        if (result.length() > this.length)
            result = result.substring(0, this.length);
        
        return result;
    }
}
